var express = require('express');
var router = express.Router();
let Users = require('../model/users');
let moment = require('moment');

//登录验证
router.post('/login', function (req, res, next) {
  let paramObj = req.body.params;
  let param = {
    userName: paramObj.userName,
    userPwd: paramObj.password,
  };
  let userModel = Users.findOne(param);
  userModel.exec(function (err, user) {
    if (err) {
      res.json({status: '1', msg: err.message});
    } else {
      if (user) {
        res.cookie("userId", user.userId, {
          path: '/',
          maxAge: 1000 * 60 * 60
        });
        res.cookie("userName", user.userName, {
          path: '/',
          maxAge: 1000 * 60 * 60
        });
        req.session['user'] = user;
        res.json({status: '0', msg: '', result: {userName: user.userName}});
      }else{
        res.json({status: '1', msg: '账号或密码错误', result: ''});
      }
    }
  });
});

//退出登录
router.post('/logOut', function (req, res) {
  res.cookie('userId', '', {
    path: '/',
    maxAge: -1,
  });
  res.cookie('userName', '', {
    path: '/',
    maxAge: -1,
  });
  res.json({
    status: 0,
    msg: '',
    result: '退出成功',
  })
});

//获取购物车列表
router.get('/cartList', function (req, res, next) {
  let userId = req.cookies.userId;
  Users.findOne({userId: userId}, function (err, doc) {
    if (err) {
      res.json({status: 1, msg: err.message,});
    } else {
      res.json({status: 0, msg: 'success', result: doc.cartList});
    }
  })
});

//删除购物车
router.post('/delCart', function (req, res, next) {
  let productId = req.body.params.productId;
  let userId = req.cookies.userId;
  Users.update({
    userId: userId,
  }, {
    $pull: {
      'cartList': {
        'productId': productId,
      }
    },
  }, function (err, doc) {
    if (err) {
      res.json({status: 1, msg: err.message, result: ''});
    } else {
      res.json({status: 0, msg: '删除成功', result: ''});
    }
  })
});

//购物车商品数量修改
router.post('/cartEdit', function (req, res, next) {
  let userId = req.cookies.userId,
    productId = req.body.params.productId,
    productNum = req.body.params.productNum,
    checked = req.body.params.checked;
  Users.update({
      //查询条件
      'userId': userId, 'cartList.productId': productId
      //更新内容
    }, {
      'cartList.$.productNum': productNum,
      'cartList.$.checked': checked,
    }, function (err, doc) {
      if (err) {
        res.json({status: 1, msg: err.message, result: ''});
      } else {
        res.json({status: 0, msg: '修改成功', result: ''});
      }
    }
  )
});

//改变商品全选的状态
router.post('/cartCheckAll', function (req, res, next) {
  let userId = req.cookies.userId,
    checkAll = req.body.params.checkAll;
  Users.findOne({'userId': userId}, function (err1, userDoc) {
    if (err1) {
      res.json({status: 1, msg: err1.message, result: ''});
    } else {
      if (userDoc) {
        userDoc.cartList.forEach(item => {
          item.checked = checkAll;
        });
        userDoc.save(function (err2, doc) {
          if (err2) {
            res.json({status: 1, msg: err1.message, result: ''});
          }
          res.json({status: 0, msg: '修改全选成功', result: checkAll});
        })
      }
    }
  })
});

//获取用户地址列表信息
router.get('/address', function (req, res, next) {
  let userId = req.cookies.userId;
  Users.findOne({'userId': userId}, function (err, userDoc) {
    if (err) {
      res.json({status: 1, msg: err.message, result: ''});
    } else {
      res.json({status: 0, msg: '获取地址信息成功', result: userDoc.addressList});
    }
  });
});

//设置地址
router.post('/setDefault', function (req, res, next) {
  let userId = req.cookies.userId;
  let addressId = req.body.params.addressId;
  Users.findOne({'userId': userId}, function (err, userDoc) {
    if (err) {
      res.json({status: 1, msg: err.message, result: ''});
    } else {
      if (userDoc) {
        userDoc.addressList.forEach(item => {
          item.isDefault = item.addressId == addressId;
        });
        userDoc.save(function (err2, doc) {
          if (err2) {
            res.json({status: 1, msg: err.message, result: ''});
          } else {
            res.json({status: 0, msg: '设置默认成功', result: ''});
          }
        })
      }
    }
  })
});

//删除地址信息
router.post('/delAddress', function (req, res, next) {
  let userId = req.cookies.userId;
  let addressId = req.body.params.addressId;
  Users.update({
    userId: userId,
  }, {
    $pull: {
      'addressList': {
        'addressId': addressId,
      }
    },
  }, function (err, doc) {
    if (err) {
      res.json({status: 1, msg: err.message, result: ''});
    } else {
      res.json({status: 0, msg: '删除地址成功', result: ''});
    }
  })
});

//付款  -- 创建订单
router.post('/payMent', function (req, res, next) {
  let userId = req.cookies.userId,
    orderTotal = req.body.params.orderTotal,
    addressId = req.body.params.addressId;
  Users.findOne({'userId': userId}, function (err, userDoc) {
    if (err) {
      res.json({status: 1, msg: err.message, result: ''});
    } else {
      if (userDoc) {
        //获取用户地址信息
        let address = {}, goodsList = [];
        userDoc.addressList.forEach(item => {
          if (item.addressId == addressId) {
            address = item;
          }
        });
        //获取用户购买的商品
        userDoc.cartList.forEach(item => {
          if (item.checked) {
            goodsList.push(item);
          }
        });
        let date = moment(new Date()).format('YYYYMMDDHHmmss');
        let order = {
          orderId: '622' + date + Math.floor(Math.random() * 1000),
          orderTotal: orderTotal,
          addressInfo: address,
          goodsList: goodsList,
          status: '1',
          createDate: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        };
        //保存用户订单信息
        userDoc.orderList.push(order);
        userDoc.save(function (err2, doc) {
          if (err2) {
            res.json({status: 1, msg: err.message, result: ''});
          } else {
            res.json({
              status: 0, msg: '保存用户订单信息成功',
              result: {orderId: order.orderId, orderTotal: order.orderTotal, createDate: order.createDate},
            });
          }
        })
      }
    }
  })
});

//获取用户订单信息
router.post('/orderInfo', function (req, res, next) {
  let userId = req.cookies.userId,
    orderId = req.body.params.orderId;

  Users.findOne({'userId': userId}, function (err, userDoc) {
    if (err) {
      res.json({status: 1, msg: err.message, result: ''});
    } else {
      if (userDoc.orderList.length > 0) {//用户有订单
        let orderTotal = 0;
        userDoc.orderList.forEach(item => {
          if (item.orderId == orderId) {
            orderTotal = item.orderTotal;
          }
        });
        if (orderTotal > 0){
          res.json({
            status : 0,msg : '获取成功',result : { orderId : orderId,orderTotal : orderTotal },
          })
        } else {
          res.json({ status : '120002',msg : '用户无此订单',result : ''});
        }
      } else {
        res.json({ status : '120001',msg : '用户未创建任何订单',result : ''});
      }
    }
  })
});

//全栈获取购物车数量
router.get('/cartCount',function (req,res,next) {
  let userId = req.cookies.userId;
  Users.findOne({ 'userId' :userId },function (err,userDoc) {
    if (err){
      res.json({status: 1, msg: err.message, result: ''});
    } else {
      let cartCount = 0;
      userDoc.cartList.forEach(item=>{
        cartCount += parseInt(item.productNum);
      });
      res.json({ status : 0,msg : '获取购物车数量成功',result : cartCount});
    }
  })
});
module.exports = router;
